<!--
* description: 供应商发货单管理-新增编辑
-->
<template>
  <section class="editCarBrand">
    <el-dialog
      v-dialogDrag
      :close-on-click-modal="false"
      :title="textMap[popupsState]"
      :append-to-body="true"
      :visible.sync="curPopupsVisible"
      @close="sendCode"
      width="1000px"
    >
      <dialogHeader
        slot="title"
        :title="textMap[popupsState]"
        :styleType="$store.state.app.dialogType"
      ></dialogHeader>
      <div class="filter-container filter-params">
        <el-row :gutter="26">
          <component
            v-for="comp in tableComponents.filter((o) => o.isMust === true)"
            :ref="comp.isRequire ? comp.isRequire + comp.compKey : comp.compKey"
            :validrule="comp.validrule"
            :key="comp.compKey"
            :codeField="comp.codeField"
            :textField="comp.textField"
            :popupsKey="comp.compKey"
            :is="comp.component"
            :code="formField[comp.codeField]"
            :text="formField[comp.textField]"
            @changeCode="getComponentCode"
            @focusCode="getFocusCode"
            :disabled="comp.disabled"
            :isRequire="comp.isRequire"
            :span="comp.span || 8"
            :isMul="comp.isMul"
            :labelName="comp.labelName"
            :readonly="comp.readonly"
            :showPlaceholder="comp.showPlaceholder"
            :dateOptionsType="comp.dateOptionsType"
            :options="comp.options"
            :dynamicIsShowSelect="true"
            :dynamicIsColumnDrop="true"
          ></component>
        </el-row>
        <el-row :gutter="34" style="margin-bottom: 5px">
          <el-col :span="24">
            <!-- <div class="dialogTitle">
              <span class="dialogTitleButton">
                <span class="dialogTip">选择供应商会清空表格的明细数据</span>
                <el-button
                  class="iconfont icon-newlyAdded"
                  @click="tableDataAdd"
                  ></el-button
                >
              </span>
            </div> -->
          </el-col>
        </el-row>
      </div>
      <!-- 表格-->
      <el-table
        ref="table"
        :data="tableData"
        style="width: 100%"
        height="300"
        border
        v-loading="listLoading"
        @selection-change="onCheckSelectChange"
      >
        <el-table-column align="center" type="selection" width="55" />
        <el-table-column label="序号" width="60" align="center">
          <template slot-scope="scope">
            <el-checkbox-group v-model="checkList">
              <el-checkbox label="复选框 A"></el-checkbox>
            </el-checkbox-group>
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                  <el-link
                    type="primary"
                    class="el-icon-delete"
                    :underline="false"
                    @click="tableDataDel(scope.$index)"
                    title="删除"
                    style="font-size: 12px"
                    >删除</el-link
                  >
                </template>
              </el-table-column> -->
          <el-table-column
          label="到货单号"
          width="150"
          align="center"
          prop="ARRIVAL_CODE"
        ></el-table-column>
           <el-table-column
          label="采购单号"
          width="150"
          align="center"
          prop="RELATION_CODE"
        ></el-table-column>
           <el-table-column
          label="备件编号"
          width="150"
          align="center"
          prop="PART_NO"
        ></el-table-column>
         <el-table-column
          label="备件名称"
          width="150"
          align="center"
          prop="PART_NAME"
        ></el-table-column>
     
        <el-table-column
          label="零件号"
          prop="COMPONENTS_NO"
          width="120"
          align="center"
        ></el-table-column>
            <el-table-column  v-if="false"
        label="到货数+" width="120" align="center">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.ARRIVAL_QTY"
              type="text"
              @input="numChange(scope)"
              style="width: 100%"
              class="tableTemplate"
            ></el-input>
          </template>
        </el-table-column>
            <el-table-column label="确认到货数+" width="120" align="center">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.ARRIVAL_QTY"
              type="number"
              @input="numChange1(scope)"
              style="width: 100%"
              class="tableTemplate"
            ></el-input>
          </template>
        </el-table-column>

        <el-table-column
          label=" 收货数"
          prop="RECEIVE_QTY"
          width="120"
          align="center"
        ></el-table-column>
         <!-- <el-table-column
          label="异常数"
          prop="ERROR_QTY"
          width="120"
          align="center"
        ></el-table-column> -->
<!--         
        <el-table-column label="采购数量+" width="120" align="center">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.PURCHASE_QTY"
              type="text"
              @input="numChange(scope)"
              style="width: 100%"
              class="tableTemplate"
            ></el-input>
          </template>
        </el-table-column> -->
         
        <!-- 要求到货时间 -->
        <!-- <el-table-column label="要求到货时间" width="100%" align="center">
          <template slot-scope="scope">
            <el-date-picker
              v-model="scope.row.RA_TIME_NEW "
              :picker-options="pickerOptions0"
              type="date"
              placeholder="选择日期"
              class="isRequire: true"
              value-format="yyyy-MM-dd"
              
            >
            </el-date-picker>
          </template>
        </el-table-column> -->

        <!-- 要求到货时间 -->

        <el-table-column
          label="备注"
          prop="REMARK"
          width="120"
          align="center"
        />
        <!-- <el-table-column
          label="销售SNP"
          prop="SNP_OUT"
          width="120"
          align="center"
        /> -->
        <!-- <el-table-column label="调拨SNP" prop="SNP_MOVE" width="120" align="center" /> -->
      </el-table>
      <!-- 表格 -->
      <div slot="footer" class="dialog-footer">
        <el-button
          v-for="comp in tableButtons"
          :key="comp.compKey"
          :type="comp.type"
          @click="comp.clickEvent"
          >{{ comp.text }}</el-button
        >
      </div>
      <editPartNoTable
        v-if="isEditShow"
        @detailPartNoClose="detailPartNoClose"
        @confirmPartNo="confirmPartNo"
        :isEditShow="isEditShow"
        :editformField="formField"
        :editTableData="tableData"
      />
    </el-dialog>
  </section>
</template>
<script>
import { formMixins } from "@/components/wms/mixins/formMixins";
import { wmsApis } from "@/api/wms/purchase/api";
import storage from "@/utils/storage";
import request from "@/utils/request";
import { message } from "ant-design-vue";
export default {
  // 组件混入对象
  mixins: [formMixins],
  components: {
    dialogHeader: () => import("@/components/dialogHeader"), //弹窗标题
    editPartNoTable: () => import("./editPartNoTable"),
  },
  watch: {
    popupsVisible(val) {
      if (val) {
        if (
          this.formField.pageId !== "" &&
          this.$route.query.pageId !== undefined &&
          this.$route.query.pageId !== this.formField.pageId
        ) {
          this.formField.pageId = this.$route.query.pageId;
          this.formField.pageName = this.$route.query.pageName;
        }
        this.formField.langLabelName = this.formField.label;
        this.backFormField = JSON.parse(JSON.stringify(this.formField));
      }
    },
  },
  data() {
    return {
      // 日期不能选择今天之前的
      pickerOptions0: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        },
      },
      // 日期不能选择今天之前的
      pickerOptions: {
        // 计费日期的约束条件
        disabledDate: this.disabledDate,
      },

      // 保存API配置对象
      apiConfig: wmsApis.savePurchase,
      // 动态组件-按钮
      tableButtons: [
        {
          compKey: "btnKey1",
          type: "primary",
          size: "small",
          clickEvent: () => this.save(),
          text: "保存", //"保存"
        },
        {
          compKey: "btnKey2",
          type: "",
          size: "small",
          clickEvent: () => this.close("1"),
          text: "关闭", //"关闭"
        },
      ],
      // 动态组件-查询条件
      tableComponents: [
        {
          compKey: "edit_compKey1",
          labelName: "采购单号",
          codeField: "PURCHASE_CODE",
          component: () => import("@/components/wms/commonInput"),
          type: "inputText",
          isMust: true,
          disabled: true,
          span: 8,
          showPlaceholder: "",
        },
        {
          compKey: "edit_compKey2",
          labelName: "供应商",
          textField: "PARTNER_SHORT_NAME",
          codeField: "SUPPLIER_CODE",
          component: () =>
            import("@/components/wms/wmsEjectWindows/wmsSupplier"),
          type: "propus",
          isMust: true,
          span: 8,
          isMul: false,
          isRequire: true,
          readonly: false,
          returnCodeField: "SUPPLIER_CODE",
          returnTextField: "PARTNER_SHORT_NAME",
          disabled: !this.isAdd(),
          changed: () => {
            this.tableData = [];
          },
        },
        {
          compKey: "edit_compKey3",
          labelName: "采购类型",
          codeField: "PURCHASE_TYPE",
          component: () => import("@/components/wms/dropdownList/dropdownList"),
          type: "dropdownList",
          isMust: true,
          isMul: false,
          span: 8,
          options: [],
          isRequire: true,
          disabled: !this.isAdd(),
        },
        {
          compKey: "edit_compKey4",
          labelName: "到货仓库",
          codeField: "WAREHOUSE_ID",
          component: () => import("@/components/wms/dropdownList/dropdownList"),
          type: "dropdownList",
          isMust: true,
          isMul: false,
          span: 8,
          options: [],
          isRequire: true,
          disabled: !this.isAdd(),
          changed: (val) => {
            if (!val) {
              return;
            }
            if (this.tableData.length == 0) {
              return;
            }
            let partNoArr = [];
            this.tableData.forEach((item) => {
              partNoArr.push(item.PART_NO);
              item.DQ_QTY = 0;
              item.AQ_QTY = 0;
              item.INBOUND_QTY = 0;
              item.OUTBOUND_QTY = 0;
            });
            request({
              url: "/mp/wm/vl/warehouse/purchase/queryPartNoStorage.do",
              method: "post",
              data: {
                WAREHOUSE_ID: val,
                PART_NOS: partNoArr.join(","),
              },
            }).then((res) => {
              if (res.listRow && res.listRow.length > 0) {
                res.listRow.forEach((item) => {
                  this.tableData.forEach((checkItem) => {
                    if (item.PART_NO == checkItem.PART_NO) {
                      checkItem.DQ_QTY = item.DQ_QTY;
                      checkItem.AQ_QTY = item.AQ_QTY;
                      checkItem.INBOUND_QTY = item.INBOUND_QTY;
                      checkItem.OUTBOUND_QTY = item.OUTBOUND_QTY;
                    }
                  });
                });
              }
              let talbeArr = this.tableData;
              this.tableData = [];
              this.$nextTick(() => {
                this.tableData = talbeArr;
              });
            });
          },
        },
        // {
        //   compKey: "edit_compKey5",
        //   labelName: "要求到货时间",
        //   codeField: "RA_TIME_NEW",
        //   component: () => import("@/components/org/datePicker/datePicker"),
        //   type: "date",
        //   isMust: true,
        //   span: 8,
        //   isRequire: true,
        //   // 日期不必填
        //   // disabled: !this.isAdd(),
        //   dateOptionsType: "3",
        //   changed: (val) => {
        //     this.tableData.forEach((item) => {
        //       this.$set(item, "RA_TIME_NEW", val);
        //     });
        //   },
        // },
      ],
      // 标题
      textMap: {
        add: "新增采购单",
        edit: "编辑采购单",
      },
      // 表单数据（无需赋值，由混入对象赋值）
      formField: {
        PURCHASE_CODE: "",
        SUPPLIER_CODE: "",
        PARTNER_SHORT_NAME: "",
        PURCHASE_TYPE: "",
        WAREHOUSE_ID: "",
        RA_TIME: "",
        PURCHASE_ID: "",
        PURCHASE_LINE_CODE:"",
        SUPPLIER_CODE:"",
        SHIPMENTS_STATUS:"",
        SHIPMENTS_STATUS_NAME:"",


      },
      //表格数据
      tableData: [],
      // 表格加载字段
      listLoading: false,
       // 选中的数据
      checkTableList: [],
      // 控制备件明细弹窗
      isEditShow: false,
    };
  },
  methods: {
    // 今天日期之前不能选择
    disabledDate(time) {
      return time.getTime() < new Date(date).getTime();
    },

    onCreated() {
      if (this.curPopupsVisible) {
        request({
          url: "/mp/wm/vl/warehouse/purchase/queryPurchaseTypeBox.do",
          method: "post",
          data: {
            PAGE_STATUS: "1",
          },
        }).then((res) => {
          if (res.listRow && res.listRow.length > 0) {
            res.listRow.map((item) => {
              this.tableComponents[2].options.push({
                label: item.PURCHASE_TYPE_NAME,
                value: item.PURCHASE_TYPE,
              });
            });
          }
        });

        request({
          url: "/mp/wm/vl/basedata/warehouseuser/queryUserByWHBox.do",
          method: "post",
          data: {
            IS_ENABLE: "1",
          },
        }).then((res) => {
          res.listRow.map((item) => {
            this.tableComponents[3].options.push({
              label: item.WAREHOUSE_NAME,
              value: item.WAREHOUSE_ID,
            });
          });
        });

        if (this.popupsState === "edit") {
          this.queryTable()
        }
      }
    },
    queryTable(){
      this.listLoading = true;
          request({
            url: "/mp/wm/vl/warehouse/ManagementPurchase/queryArrivalD.do",
            method: "post",
            data: {
              pageIndex: 1,
              pageSize: 999,
              PURCHASE_CODE: this.formField.PURCHASE_CODE,
            },
          })
            .then((res) => {
              this.listLoading = false;
              if (res.result === "1") {
                if (res.listResult) {
                  this.tableData = res.listResult.rows;
                }
              } else {
                if (res.msg || res.debugMsg) {
                  this.$message({
                    message: res.debugMsg ? res.debugMsg : res.msg,
                    uration: 2000,
                  });
                }
              }
            })
            .catch((err) => {
              console.info(err);
              this.listLoading = false;
            });
    },
    confirmPartNo(checkList) {
      this.isEditShow = false;
      checkList.forEach((item) => {
        this.tableData.push(item);
      });
      console.log(this.tableData)
    },
    
    // 采购数量change事件
    numChange1(scope) {
      if (scope.row.ARRIVAL_QTY0 < 1) {
        scope.row.ARRIVAL_QTY0 = "";
      }
      scope.row.ARRIVAL_QTY0 = (scope.row.ARRIVAL_QTY0 + "").replace(
        /[^\d]/g,
        ""
      );
      

    },

    // 新增按钮 点击事件
    tableDataAdd() {
      if (!this.formField.SUPPLIER_CODE) {
        this.$message({
          message: "请选择供应商",
        });
        return;
      }
      if (!this.formField.WAREHOUSE_ID) {
        this.$message({
          message: "请选择仓库",
        });
        return;
      }
      this.isEditShow = true;
    },
    detailPartNoClose() {
      this.isEditShow = false;
    },
    //  删除按钮 点击事件
    tableDataDel() {
      // 选中的数据
        const seletedDatas = this.$refs.table.selection;
        console.log(seletedDatas);
      if (seletedDatas.length != 0) {
        this.$confirm("确定要作废吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          center: true,
        }).then(() => {
          request({
            url: "/mp/wm/vl/warehouse/ManagementPurchase/purchaseDInvalid.do",
            method: "post",
            data: {
              IDS: seletedDatas,
            },
          }).then((res) => {
            if (res.result == "1") {
              this.$message({
                message: res.msg,
                type: "success",
              });
              this.queryTable();
            }
            else {
              this.$message({
                message: res.msg,
                type: "success",
              });
            }
          });
        });
      } else {
        this.$message({
          message: "请选择一条数据",
        });
      }
    },
      // 启用
 enable() {
      // 选中的数据
        const seletedDatas = this.$refs.table.selection;
        console.log(seletedDatas);
      if (seletedDatas.length != 0) {
        this.$confirm("确定要启用吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          center: true,
        }).then(() => {
          request({
            url: "/mp/wm/vl/warehouse/ManagementPurchase/purchaseDstart.do",
            method: "post",
            data: {
              IDS: seletedDatas,
            },
          }).then((res) => {
            if (res.result == "1") {
              this.queryTable();
              this.$message({
                message: res.msg,
                type: "success",
              });
            }
            else {
              this.$message({
                message: res.msg,
                type: "success",
              })
            }
          });
        });
      } else {
        this.$message({
          message: "请选择一条数据",
        });
      }
      // 批量删除
      // const seletedDatas = this.$refs.table.selection;
      // if (seletedDatas.length === 0) {
      //   this.$message({
      //     message: "请至少选择一条数据",
      //   });
      //   return;
      // }
      // this.$confirm("您确定是否要进行此操作？", "提示", {
      //   confirmButtonText: "确定",
      //   cancelButtonText: "取消",
      //   center: true,
      // })
      //   .then(() => {
      //     // 批量删除
      //     const arr = [];
      //     this.tableData.forEach((item) => {
      //       const filterData = seletedDatas.filter(
      //         (element) => element.PART_NO === item.PART_NO
      //       );
      //       if (filterData.length === 0) {
      //         arr.push(item);
      //       }
      //     });
      //     this.tableData = arr;
      //     this.$message({
      //       type: "success",
      //       message: "作废成功!",
      //     });
      //   })
      //   .catch(() => {});
    },
    //保存
    save() {
      
      //   const seletedDatas = this.$refs.table.selection;
        console.log(this.tableData);
      // if (seletedDatas.length != 0) {
        this.$confirm("确定要保存吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          center: true,
        })
        .then(() => {
          request({
            url: "/mp/wm/vl/warehouse/ManagementPurchase/saveArrivalD.do",
            method: "post",
            data: {
              IDS: this.tableData,
            },
          }).then((res) => {
            if (res.result != "0") {
              this.queryTable();
              this.$message({
                message: res.msg,
                type: "success",
              });
            }
              else {
              this.$message({
                // message: res.msg,
                  message: res.debugMsg ? res.debugMsg : res.msg,
                type: "success",
              })
            }
            
          });
        });
      
      // }
      // 保存
      // let flag = false;
      // if (this.tableData.length < 1) {
      //   this.$message({
      //     message: "至少保存一条采购明细",
      //   });
      //   return;
      // }
      // this.tableData.forEach((item) => {
      //   if (!item.PURCHASE_QTY || !item.RA_TIME) {
      //     flag = true;
      //   }
      // });
      // if (flag) {
      //   this.$message({
      //     message: "明细中的采购数量未输入或者要求到货日期未选择",
      //   });
      //   return;
      // }

      // this.$utils.validataMoth(this, "validpopup");
      // if (this.valid) {
      //   var saveObj = JSON.parse(JSON.stringify(this.formField));
      //   saveObj.PurchaseD = this.tableData;
      //   //保存表单
      //   this.saveForm(saveObj);
      //   storage.remove(this.$route.query.pageCode);
      // }
    },
      //  当选择项发生变化时会触发该事件
    onCheckSelectChange(selection) {
     
      this.checkTableList = selection;
    },
  //  关单
    single() {
     
      if (this.checkTableList.length > 0) {
       
        // if (this.checkTableList.length !== this.tableData.length) {
        //   this.$message({
        //     message: "请选择所有行数据",
        //     type: "warn"
        //   });
        //   return false;
        // }
        this.$confirm("确认要执行此操作吗？", "提示", {
          
          confirmButtonText: "确认",
          cancelButtonText: "取消"
        }).then(() => {
            request({
              url: "/mp/wm/vl/warehouse/purchase/purchaseDToClose.do",
              method: "post",
              data: {
              purchaseDToClose: this.checkTableList
              }
            }).then(res => {
              if (res.result === "1") {
                this.$message({
                  message: "关单成功",
                  type: "success"
                });
                // this.$emit("detailClose", true);
                // 关闭页面的按钮
                 this.queryTable();
              } else {
                this.$message({
                  message: res.debugMsg ? res.debugMsg : res.msg,
                  type: "warn"
                });
              }
            });
          })
          .catch(err => {
            console.info(err);
          });
      } else {
        this.$message({
          message: "请选择一条数据"
        });
      }
    },
  },
};
</script>
<style type="text/css" lang="scss" scoped>
.dialogTitle {
  text-align: left;
  overflow: hidden;
}
.dialogTitleButton {
  float: right;
}
/deep/ .tableTemplate .el-input__inner {
  border: none;
}
.dialogTip {
  color: red;
  margin-right: 10px;
  font-size: 12px;
}
.strlke {
}
.el-table .el-date-editor {
  width: 100%;
}
.strlke {
 margin-right: 15px;
}
</style>
